package com.baomidou.springwind.controller.supply;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.springwind.controller.BaseController;
import com.baomidou.springwind.entity.NetworkDelivery;
import com.baomidou.springwind.entity.NetworkSupply;
import com.baomidou.springwind.mapper.NetworkDeliveryDao;
import com.baomidou.springwind.pojo.SiteCoverBuilder;
import com.baomidou.springwind.pojo.SiteSelection;
import com.baomidou.springwind.pojo.SiteSelectionBuilder;
import com.baomidou.springwind.service.NetworkSupplyService;
import com.baomidou.springwind.utils.CityUtil;
import com.baomidou.springwind.utils.ParamMap;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baomidou.springwind.mapper.NetworkSupplyDao;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 物流供应链
 * </p>
 *
 * @Author huangtao
 * @Date 2017-8-21
 */
@Controller
@RequestMapping("/network/supply")
public class TransportController extends BaseController {

    @Autowired
    private NetworkSupplyService networkSupplyService;

    @Autowired
    private NetworkSupplyDao networkSupplyDao;

    @Autowired
    private NetworkDeliveryDao networkDeliveryDao;

    private DecimalFormat df = new DecimalFormat("###,##0.00");

    /**
     * 客户分析主界面
     */
    @RequestMapping("/transport")
    @Permission("1001")
    public String customGroup(Model model) {
        EntityWrapper<NetworkSupply> wrapper1 = new EntityWrapper<NetworkSupply>();
        wrapper1.setSqlSelect("branch_center branchCenter");
        wrapper1.eq("batch_id", getProjectId());
        wrapper1.groupBy("branch_id");
        model.addAttribute("branchCenterList", networkSupplyService.selectObjs(wrapper1));
        EntityWrapper<NetworkSupply> wrapper2 = new EntityWrapper<NetworkSupply>();
        wrapper2.setSqlSelect("primary_sales primarySales");
        wrapper2.eq("batch_id",getProjectId());
        wrapper2.groupBy("primary_sales");
        model.addAttribute("primarySaleList", networkSupplyService.selectObjs(wrapper2));
        return pjaxPath("/lpp/network/supply/transport/main", model);
    }

    /**
     * 客户分析主界面
     */
    @RequestMapping("/test")
    @Permission("1001")
    public String test(Model model) {
        EntityWrapper<NetworkDelivery> wrapper = new EntityWrapper<NetworkDelivery>();
        wrapper.eq("batch_id", getProjectId());
        List<NetworkDelivery> networkDeliveries = networkDeliveryDao.selectList(wrapper);
        List<NetworkDelivery> firstDeliveryList = new ArrayList<NetworkDelivery>();
        List<NetworkDelivery> secondDeliveryList = new ArrayList<NetworkDelivery>();
        for (NetworkDelivery delivery : networkDeliveries) {
            if (delivery.getType() == 1) {
                firstDeliveryList.add(delivery);
            } else if (delivery.getType() == 2) {
                secondDeliveryList.add(delivery);
            }
        }
        SiteSelectionBuilder builder = new SiteSelectionBuilder(firstDeliveryList, secondDeliveryList);
        List<SiteSelection> siteSelectionList = builder.build();
        SiteCoverBuilder builder1 = new SiteCoverBuilder(siteSelectionList, secondDeliveryList);
        Map<SiteSelection, List<SiteSelection>> map = builder1.build();
        model.addAttribute("siteList", siteSelectionList);
        model.addAttribute("oldSiteList", builder.getOrginSiteList());
        return "/lpp/network/supply/transport/test";
    }


    @ResponseBody
    @Permission("1001")
    @RequestMapping("/transport/bar1")
    public String getBar1() {
        Map<String, Object> pm = getParameterMap();
        pm.put("batchId", getProjectId());
        List<Map<String, Object>> dataList = networkSupplyDao.selectTransportTimeStat(pm);
        if(dataList.size()==0){
            String message="查询数据异常";
            return callbackFail(message);
        }
        JSONObject ret = new JSONObject();
        JSONArray time = new JSONArray();
        JSONArray days = new JSONArray();
        JSONArray delay = new JSONArray();
        JSONArray ontime = new JSONArray();
        for (Map<String, Object> map : dataList) {
            time.add(map.get("time"));
            days.add(map.get("days"));
            delay.add(map.get("delay"));
            ontime.add(map.get("ontime"));
        }
        ret.put("time", time);
        ret.put("days", days);
        ret.put("delay", delay);
        ret.put("ontime", ontime);
        return callbackSuccess(ret);
    }
    public String getPrimary(String branch){
        ParamMap<String,Object> pm=new ParamMap<String, Object>();
        pm.put("batchId",getProjectId());
        pm.put("operatorId",getCurrentUserId());
        pm.put("branchId",branch);
        List<Map<String, Object>> mapList = networkSupplyDao.selectPrimary1(pm);
        if(mapList!=null){
            return mapList.get(0).get("primarySales").toString();
        }
        return null;
    }
    public String getBranch(){
        ParamMap<String,Object> pm=new ParamMap<String, Object>();
        pm.put("batchId",getProjectId());
        pm.put("operatorId",getCurrentUserId());
        List<Map<String, Object>> mapList = networkSupplyDao.selectBranch(pm);
        if(mapList!=null){
            return mapList.get(0).get("branchId").toString();
        }
        return null;
    }

    @ResponseBody
    @Permission("1001")
    @RequestMapping("/transport/option")
    public String getOption1() {
        JSONObject ret = new JSONObject();
        String branch=request.getParameter("center");
        EntityWrapper<NetworkSupply> wrapper1 = new EntityWrapper<NetworkSupply>();
        wrapper1.setSqlSelect("primary_sales primarySales");
        wrapper1.eq("batch_id",getProjectId());
        wrapper1.eq("branch_center",branch);
        wrapper1.groupBy("primary_sales");
        List<NetworkSupply> list1=networkSupplyService.selectList(wrapper1);
        ret.put("option",list1);
        return callbackSuccess(ret);
    }


    @ResponseBody
    @Permission("1001")
    @RequestMapping("/transport/bar4")
    public String getBar4() {
        Map<String, Object> pm = getParameterMap();
        pm.put("batchId", getProjectId());
        List<Map<String, Object>> dataList = networkSupplyDao.selectTransportPickUpStat(pm);
        if(dataList.size()==0){
            String message="查询数据异常";
            return callbackFail(message);
        }
        JSONObject ret = new JSONObject();
        JSONArray time = new JSONArray();
        JSONArray days = new JSONArray();
        Long delay = 0L;
        Long ontime = 0L;
        for (Map<String, Object> map : dataList) {
            time.add(map.get("time"));
            days.add(map.get("days"));
            delay += Long.valueOf(map.get("delay").toString());
            ontime += Long.valueOf(map.get("ontime").toString());
        }
        ret.put("time", time);
        ret.put("days", days);
        ret.put("delay", delay);
        ret.put("ontime", ontime);
        return callbackSuccess(ret);
    }

    @ResponseBody
    @Permission("1001")
    @RequestMapping("/transport/bar5")
    public String getBar5() {
        Map<String, Object> pm = getParameterMap();
        pm.put("batchId", getProjectId());
        List<Map<String, Object>> dataList = networkSupplyDao.selectTransportArrivalStat(pm);
        if(dataList.size()==0){
            String message="查询数据异常";
            return callbackFail(message);
        }
        JSONObject ret = new JSONObject();
        JSONArray time = new JSONArray();
        JSONArray days = new JSONArray();
        for (Map<String, Object> map : dataList) {
            time.add(map.get("time"));
            days.add(map.get("days"));
        }
        ret.put("time", time);
        ret.put("days", days);
        return callbackSuccess(ret);
    }

    /**
     * 客户分析主界面
     */
    @RequestMapping("/transport_old")
    @Permission("1001")
    public String transportOld(Model model) {
        EntityWrapper<NetworkDelivery> wrapper = new EntityWrapper<NetworkDelivery>();
        wrapper.setSqlSelect("id,name");
        wrapper.eq("batch_id", getProjectId());
        wrapper.eq("type", 1);
        model.addAttribute("firstList", networkDeliveryDao.selectMaps(wrapper));
        return pjaxPath("/lpp/network/supply/cost/main", model);
    }

    /**
     * 客户分析主界面
     */
    @RequestMapping("/transport_new")
    @Permission("1001")
    public String transportNew(Model model) {
        EntityWrapper<NetworkDelivery> wrapper = new EntityWrapper<NetworkDelivery>();
        wrapper.eq("batch_id", getProjectId());
        List<NetworkDelivery> networkDeliveries = networkDeliveryDao.selectList(wrapper);
        if(networkDeliveries.size()==0){
            return pjaxPath("/lpp/network/supply/cost/main_new", model);
        }
        List<NetworkDelivery> firstDeliveryList = new ArrayList<NetworkDelivery>();
        List<NetworkDelivery> secondDeliveryList = new ArrayList<NetworkDelivery>();
        for (NetworkDelivery delivery : networkDeliveries) {
            if (delivery.getType() == 1) {
                firstDeliveryList.add(delivery);
            } else {
                secondDeliveryList.add(delivery);
            }
        }
        SiteSelectionBuilder builder = new SiteSelectionBuilder(firstDeliveryList, secondDeliveryList);
        List<SiteSelection> siteSelectionList = builder.build();
        model.addAttribute("firstList", siteSelectionList);
        return pjaxPath("/lpp/network/supply/cost/main_new", model);
    }

    /**
     * 运输成本(老)
     */
    @ResponseBody
    @RequestMapping("/transport_old_data")
    @Permission("1001")
    public String getData(Model model) {
        ParamMap<String, Object> pm = getParameterMap();
        NetworkDelivery first = new NetworkDelivery();
        first.setId(pm.getLong("id"));
        first.setBatchId(Long.valueOf(getProjectId()));
        first = networkDeliveryDao.selectOne(first);
        EntityWrapper<NetworkDelivery> wrapper = new EntityWrapper<NetworkDelivery>();
        wrapper.eq("pid", pm.getLong("id"));
        wrapper.eq("batch_id",getProjectId());
        List<NetworkDelivery> secondList = networkDeliveryDao.selectList(wrapper);
        if(secondList.size()==0){
            String message="查询数据异常";
            return callbackFail(message);
        }
        JSONObject ret = calc(pm, first, secondList);
        return callbackSuccess(ret);
    }

    /**
     * 运输成本(新)
     */
    @ResponseBody
    @RequestMapping("/transport_new_data")
    @Permission("1001")
    public String getDataNew() {
        ParamMap<String, Object> pm = getParameterMap();
        EntityWrapper<NetworkDelivery> wrapper = new EntityWrapper<NetworkDelivery>();
        wrapper.eq("batch_id", getProjectId());
        List<NetworkDelivery> networkDeliveries = networkDeliveryDao.selectList(wrapper);
        List<NetworkDelivery> firstDeliveryList = new ArrayList<NetworkDelivery>();
        List<NetworkDelivery> secondDeliveryList = new ArrayList<NetworkDelivery>();
        for (NetworkDelivery delivery : networkDeliveries) {
            if (delivery.getType() == 1) {
                firstDeliveryList.add(delivery);
            } if (delivery.getType() == 2)  {
                secondDeliveryList.add(delivery);
            }
        }
        SiteSelectionBuilder builder = new SiteSelectionBuilder(firstDeliveryList, secondDeliveryList);
        List<SiteSelection> siteSelectionList = builder.build();
        SiteCoverBuilder builder1 = new SiteCoverBuilder(siteSelectionList, secondDeliveryList);
        Map<SiteSelection, List<SiteSelection>> map = builder1.build();
        NetworkDelivery first = null;
        List<NetworkDelivery> secondList = new ArrayList<NetworkDelivery>();
        for (SiteSelection siteSelection : map.keySet()) {
            if (siteSelection.getName().equals(pm.getString("name"))) {
                first = SiteSelection.transform(siteSelection);
                for (SiteSelection child : map.get(siteSelection)) {
                    secondList.add(SiteSelection.transform(child));
                }
            }
        }
        JSONObject ret = calc(pm, first, secondList);
        return callbackSuccess(ret);
    }

    private JSONObject calc(ParamMap<String, Object> pm, NetworkDelivery first, List<NetworkDelivery> secondList) {
        List<Double> distanceList = calcDistance(first, secondList);
        printDistance(first,secondList,distanceList);
        double unitPrice = pm.getDouble("unitPrice");
        double volume = pm.getDouble("volume");
        double load = pm.getDouble("load");
        double otherExpenses = pm.getDouble("otherExpenses");
        double storeUnitPrice = pm.getDouble("storeUnitPrice");
        double area = pm.getDouble("area");
        double months=pm.getDouble("months");
        JSONArray classify = new JSONArray();
        JSONObject data;
        double totalOrder = 0d;
        double totalDistance = 0d;
        double totalCost = 0d;
        double totalVehicle = 0d;
        double renta = storeUnitPrice * area * 30;
        for (int i = 0; i < secondList.size(); i++) {
            data = new JSONObject();
            NetworkDelivery delivery = secondList.get(i);
            double distance = distanceList.get(i);
            double vehicle = (int) Math.ceil(delivery.getOrderQuantity().doubleValue() * volume / load / 30/months);
            double cost = unitPrice * vehicle * distance + otherExpenses;
            data.put("name", delivery.getName());
            data.put("coordinateX", delivery.getCoordinateX());
            data.put("coordinateY", delivery.getCoordinateY());
            data.put("order", delivery.getOrderQuantity());
            data.put("distance", distance);
            data.put("cost", cost);
            data.put("vehicle", vehicle);
            totalOrder += delivery.getOrderQuantity().doubleValue();
            totalDistance += distance;
            totalCost += cost;
            totalVehicle += vehicle;
            classify.add(data);
        }
        totalCost += renta;
        JSONObject ret = new JSONObject();
        ret.put("data", classify);
        ret.put("totalOrder", df.format(totalOrder));
        ret.put("totalDistance", df.format(totalDistance));
        ret.put("totalCost", df.format(totalCost));
        ret.put("totalVehicle", totalVehicle);
        ret.put("renta", df.format(renta));
        return ret;
    }
    //用excel写出距离
    public void printDistance(NetworkDelivery first,List<NetworkDelivery> secondList,List<Double> distanceList){
        try{
            HSSFWorkbook wb=new HSSFWorkbook();
            HSSFSheet sheet=wb.createSheet("sheet");
            HSSFRow row=sheet.createRow(0);
            HSSFCell cell1=row.createCell(0);
            cell1.setCellValue("一级配送中心");
            HSSFCell cell2=row.createCell(1);
            cell2.setCellValue("二级配送中心");
            HSSFCell cell3=row.createCell(2);
            cell3.setCellValue("距离");
            int i=1;
                for (int i1=0;i1<distanceList.size();i1++){
                    HSSFRow row1=sheet.createRow(i++);
                    HSSFCell cellcenter=row1.createCell(0);
                    cellcenter.setCellValue(first.getName());
                    HSSFCell celldelivery=row1.createCell(1);
                    celldelivery.setCellValue(secondList.get(i1).getName());
                    HSSFCell distance=row1.createCell(2);
                    distance.setCellValue(distanceList.get(i1));
                }
            try {
                String s="d:\\daoxiang.xls";
                FileOutputStream fileOutputStream=new FileOutputStream(s);
                wb.write(fileOutputStream);
                fileOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
          //  return output.toByteArray();
        }catch (Exception e){
            System.out.println("报错");
        }
    }

    /**
     * 计算距离
     */
    private List<Double> calcDistance(NetworkDelivery first, List<NetworkDelivery> secondList) {
        List<Double> distanceList = new ArrayList<Double>(secondList.size());
        double distance;
        for (NetworkDelivery second : secondList) {
            distance = CityUtil.getDistance(first.getCoordinateX().doubleValue(), first.getCoordinateY().doubleValue(),
                    second.getCoordinateX().doubleValue(), second.getCoordinateY().doubleValue());
            distanceList.add(distance);
        }
        return distanceList;
    }
    @RequestMapping("/cost/bar11")
    @Permission("1001")
    public String bar11(Long batchId,Model model) {
        model.addAttribute("batchId",batchId);
        return "/lpp/network/supply/cost/bar1";
    }
    @RequestMapping("/cost/bar21")
    @Permission("1001")
    public String bar21(Long batchId,Model model) {
        model.addAttribute("batchId",batchId);
        return "/lpp/network/supply/cost/bar2";
    }
}
